//
//  AppDelegate.m
//  DaoZiJinFu
//
//  Created by woker on 16/6/23.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabBar.h"
#import <AVFoundation/AVFoundation.h>

#import "UMMobClick/MobClick.h"

#define timeLine 120

@interface AppDelegate () {
    NSTimer *timer;
    NSInteger count;
    __block UIBackgroundTaskIdentifier bgTask;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //初始化IQKeyboardManager
    IQKeyboardManager* manager = [IQKeyboardManager sharedManager];
    manager.enable=YES;
    manager.shouldResignOnTouchOutside=YES;
    manager.shouldToolbarUsesTextFieldTintColor=YES;
    manager.enableAutoToolbar=NO;
    
    [self setUMengAnalytics];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"AppFirstLoad"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AppFirstLoad"];
        [theUser synchronize];
        self.window.rootViewController = [[MainTabBar alloc] init];
        return YES;
    }
    self.window.rootViewController = [[MainTabBar alloc] init];
    if (userValue(ISLOGIN) == nil) {
        [theUser setObject:[NSNumber numberWithBool:NO] forKey:ISLOGIN];
    }
    DZUserInfo.userInfo = [DZInfos mj_objectWithKeyValues:userValue(@"DZUserInfomation")];
    [self getIndexInfo];
    return YES;
}

// 友盟统计
- (void)setUMengAnalytics {
    UMConfigInstance.appKey = @"58feac7cf5ade46c60000331";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];
}

- (void)getIndexInfo {
    __block NSInteger rns_expire = 0;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.httpMethod = @"GET";
    request.requestUrl = @"index/index";
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            DZRnsAndSid *rns = [DZRnsAndSid mj_objectWithKeyValues:model.data];
            if (rns.rns) {
                [theUser setObject:rns.rns forKey:RNS];
            }
            if (rns.sid) {
                [theUser setObject:rns.sid forKey:SID];
            }
            rns_expire = rns.rns_expire;
        }
        [theUser synchronize];
        if (rns_expire == 0 && DZUserInfo.userInfo.mobile) {
            DZRequestUtil *request = [[DZRequestUtil alloc] init];
            request.requestUrl = @"Index/login";
            request.params = @{@"mobile":DZUserInfo.userInfo.mobile};
            [DZNetAPI request:request success:^(id response) {
                NSLog(@"%@",response);
                DZResponse *info = [DZResponse mj_objectWithKeyValues:response];
                if (info.rt == 1) {
                    if (info.data[@"uInfo"][LOGIN_TOKEN]) {
                        [theUser setObject:info.data[@"uInfo"][LOGIN_TOKEN] forKey:LOGIN_TOKEN];
                    }
                    [theUser setObject:[NSNumber numberWithBool:YES] forKey:ISLOGIN];
                    [CommTools setUserInfo:response];
                }else {
                    [theUser setObject:[NSNumber numberWithBool:NO] forKey:ISLOGIN];
                    [CommTools removeAllSet];
                }
            } failure:^(NSError *error) {
            }];
        }
        if (rns_expire == 1) {
            [theUser setObject:[NSNumber numberWithBool:YES] forKey:ISLOGIN];
            DZRequestUtil *request = [[DZRequestUtil alloc] init];
            request.requestUrl = @"User/getUserInfo";
            request.httpMethod = @"GET";
            [DZNetAPI request:request success:^(id response) {
                NSLog(@"%@",response);
                DZResponse *info = [DZResponse mj_objectWithKeyValues:response];
                if (info.rt == 1) {
                    [CommTools setUserInfo:response];
                }
            } failure:^(NSError *error) {
               NSLog(@"%@",error);
            }];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

}

- (void)applicationWillTerminate:(UIApplication *)application {
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.iwoker.DaoZiJinFu" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DaoZiJinFu" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"DaoZiJinFu.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
